var screens = {};
function FLogRegisterScreen (name, method) {
    screens["\""+name+"\""] = method;
}

function FLogInstallBuildingOverview () {
    var tds = document.getElementsByTagName ("td");
    var label = "Ship"
    var jobs = null;
    for (var i=0, len=tds.length; i<len; i++) {
        if (tds[i].textContent == label){
            if (tds[i].getAttribute("onmousedown") == null) {
                label = "Jobs";
                continue;
            }
            jobs = tds[i];
            break;
        }
    }
    if (!jobs) return;
    
    var newJobs = jobs.cloneNode (false);
    newJobs.textContent = "Fed\nLogger";
    //newJobs.setAttribute ("onmousedown", "this.style.background='url(file://c:/temp/pardus/images_standardhq/tabactive.png)';this.style.cursor='default';this.onmouseout='';FLogInstallFLogBuildings()");
    newJobs.setAttribute ("onmousedown", "this.style.cursor='default';this.onmouseout='';FLogInstallFLogBuildings()");
    newJobs.id = "po_flog_overview_tab";
    var tabs = jobs.parentNode.cells.length;
    var w = Number (jobs.parentNode.parentNode.parentNode.getAttribute ("width")) / tabs;
    jobs.parentNode.appendChild (newJobs);
    jobs.parentNode.parentNode.parentNode.setAttribute ("width", String(w*(tabs+1)));
}

function FLogRestoreTabs () {
    var tds = document.getElementsByTagName ("td");
    var label = "Ship";
    var jobs = null;
    for (var i=0, len=tds.length; i<len; i++) {
        if (tds[i].textContent == label){
            if (tds[i].getAttribute("onmousedown") == null) {
                label = "Jobs";
                continue;
            }
            jobs = tds[i];
            break;
        }
    }
    if (!jobs) return;
    var tbl = jobs.parentNode.parentNode.parentNode;
    
    for (var i=0, len=tbl.rows[0].cells.length; i<len; i++) {
        var acell = tbl.rows[0].cells[i];
        if (acell.getAttribute ("onmousedown") == null) {
            acell.setAttribute ("onmousedown", "document.location.href='"+ document.location.href +"'");
            acell.setAttribute ("style", jobs.getAttribute ("style"));
            acell.setAttribute ("onmouseout", jobs.getAttribute ("onmouseout"));
            acell.setAttribute ("onmouseover", jobs.getAttribute ("onmouseover"));
            break;
        }
    }
}

function FLogInstallFLogBuildings () {
    FLogRestoreTabs ();
    var server = top.FLogGetServer ();
    
    var tab = document.getElementById ("po_flog_overview_tab");
    var tbl = tab.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
    
    var elem = tbl;
    var content = null;
    for (var i=0; i<10; i++) {
        elem = elem.nextSibling;
        try {
            if (elem.nodeName.toUpperCase() == "TABLE") {
                content = elem;
                break;
            }
        } catch (e) {}
    }
    if (content) {
        content.innerHTML = "<tbody><tr><td align=center id='po_flog_screen_links'></td></tr>\
                            <tr><td id='po_flog_overview_sector_td'><span>Sector </span><input id='po_flog_overview_sector_inp' type='textbox' value='"+server.sector+"'></input> \
                            <input type=submit value='Select'onClick='FLogSetSector();void(0);'></input></td></tr>\
                            <tr><td><table id='po_flog_overview_data'><tbody></tbody></table></td></tr>\
                            </tbody>";
        var view = localStorage.getItem ("flog_last_view");
        var first = true;
        var links = "";
        for (name in screens) {
            if (first) first = false;
            else {
                links += "<span> - </span>";
            }
            links += "<a id='"+name+"' href='javascript:FLogShowScreen("+name+");void(0);'>"+name.substr(1, name.length-2)+"</a>";
        }
        document.getElementById("po_flog_screen_links").innerHTML = links;
        var method = screens[view];
        if (screens.hasOwnProperty(view)) {
            FLogShowScreen (view);
        } else {
            FLogShowScreen ("\"Overview\"");
        }
    }
}

function FLogShowScreen (name) {
    if (name[0] != "\"") name = "\""+name+"\"";
    localStorage.setItem ("flog_last_view", name);
    var links = document.getElementById("po_flog_screen_links").getElementsByTagName("a");
    for (var i=0; i<links.length; i++) {
        var link = links[i];
        var lname = link.getAttribute("id"); //.substr (1, link.getAttribute("id").length-2);
        if (lname == name) {
            link.setAttribute ("style", "color:lime; font-weight:bold");
        } else {
            link.setAttribute ("style", "color:white");
        }
    }
    var method = screens[name];
    method ();
}

function FLogShowData () {
    var server = top.FLogGetServer ();
    server.AddNotification ("flog_overview_overview", FLogShowData);
    var data = document.getElementById ("po_flog_overview_data");
    data.firstChild.innerHTML = "";
    
    var row = document.createElement ("tr");
    data.firstChild.appendChild (row);
    row.innerHTML = "<td></td><th align=center colspan=11>Basic data</th>";

    var row = document.createElement ("tr");
    data.firstChild.appendChild (row);
    row.innerHTML = "<th>Tile ID</th><th>Sector</th><th>Coords</th><th>Type</th><th>Name</th><th>Population</th><th>Rings</th><th>Building type</th><th>Owner</th><th>Owner's alliance</th><th>Faction</th><th>Last update</th>";
        
        
    for (key in server.data) {
        var val = server.data[key]["facility"];
        var sq = server.data[key]["squadrons"];
        var row = document.createElement ("tr");
        data.firstChild.appendChild (row);
        if (!val) {
            row.innerHTML = "<th>"+key+"</th><td colspan=12 align=center>No basic data available</td>";
            continue;
        }
        row.innerHTML = "<th>"+key+"</th>\
                        <td align=right>"+val["sector"]+"</td>\
                        <td align=left>"+val["coords"]+"</td>\
                        <td>"+val["facility_type"]+"</td>\
                        <td>"+(val["name"]?val["name"]:"---")+"</td>\
                        <td>"+(val["population"]?val["population"]:"---")+"</td>\
                        <td>"+(val["rings"]?val["rings"]:"---")+"</td>\
                        <td>"+(val["building_type"]?val["building_type"]:"---")+"</td>\
                        <td>"+(val["owner"]?val["owner"]:"---")+"</td>\
                        <td>"+(val["owner_alliance"]?val["owner_alliance"]:"---")+"</td>\
                        <td>"+(val["faction"]?val["faction"]:"---")+"</td>\
                        <td>"+server.LastUpdateAgo(val["timestamp"])+"</td>";
//        if (!sq) {
//            row.innerHTML += "<td colspan=2 align=center>---</td>"
//        } else {
//            row.innerHTML += "<td>"+sq["squadrons"]+"</td>\
//                            <td>"+server.LastUpdateAgo(sq["timestamp"])+"</td>";
//        }
    }
}
FLogRegisterScreen ("Overview", FLogShowData);

function FLogShowMOs () {
    var server = top.FLogGetServer ();
    server.AddNotification ("flog_overview_overview", FLogShowMOs);
    var data = document.getElementById ("po_flog_overview_data");
    data.firstChild.innerHTML = "";
    
    var row = document.createElement ("tr");
    data.firstChild.appendChild (row);
    row.innerHTML = "<td></td><th align=center colspan=7>Basic data</th><th align=center colspan=5>Stock</th>";

    var row = document.createElement ("tr");
    data.firstChild.appendChild (row);
    row.innerHTML = "<th>Tile ID</th><th>Sector</th><th>Coords</th><th>Owner</th><th>Owner's alliance</th><th>Faction</th><th>Condition</th><th>Last update</th>\
                    <th>Energy</th><th>Fuel</th><th>Ticks till empty</th><th>Stock last updated</th>";
    
    for (key in server.data) {
        var val = server.data[key]["facility"];
        if (!val || val["building_type"] != "Military Outpost") continue;
        
        var st = server.data[key]["stock"];
        var row = document.createElement ("tr");
        data.firstChild.appendChild (row);
        if (!val) {
            row.innerHTML = "<th>"+key+"</th><td colspan=6 align=center>No basic data available</td>";
            continue;
        }
        row.innerHTML = "<th>"+key+"</th>\
                        <td align=right>"+val["sector"]+"</td>\
                        <td align=left>"+val["coords"]+"</td>\
                        <td>"+(val["owner"]?val["owner"]:"---")+"</td>\
                        <td>"+(val["owner_alliance"]?val["owner_alliance"]:"---")+"</td>\
                        <td>"+(val["faction"]?val["faction"]:"---")+"</td>\
                        <td>"+(val["building_condition"]?val["building_condition"]:"---")+"</td>\
                        <td>"+server.LastUpdateAgo(val["timestamp"])+"</td>";
        if (!st) {
            row.innerHTML += "<td colspan=4 align=center>---</td>"
        } else {
            var auto = "";
            if (st["last_tick"]) {
                auto = "<span style='color:red;font-weight:bold'> A</span>";
            }
            var min = (st["stock"]["2"][1] > st["stock"]["16"][1])?st["stock"]["16"][1]:st["stock"]["2"][1];
            var ticks = Math.floor (min/5);
            if (ticks < 3) {
                ticks = "<div style='color:red;font-weight:bold'>"+ticks+"</div>";
            } else if (ticks < 5) {
                ticks = "<div style='color:yellow;font-weight:bold'>"+ticks+"</div>";
            } else {
                ticks = "<div style='color:lime;font-weight:bold'>"+ticks+"</div>";
            }
            row.innerHTML += "<td>"+st["stock"]["2"][1]+"t</td>\
                            <td>"+st["stock"]["16"][1]+"t</td>\
                            <td>"+ticks+"</td>\
                            <td>"+server.LastUpdateAgo(st["timestamp"])+auto+"</td>";
        }
    }
}
FLogRegisterScreen ("MOs", FLogShowMOs);
 
function FLogSetSector (value) {
    var server = top.FLogGetServer ();
    server.SetSector (document.getElementById("po_flog_overview_sector_inp").value);
    server.ClearData ();
    server.RefreshData ();
}


FLogInstallBuildingOverview ();
